package com.taritari.utils;

import com.taritari.entity.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

/**
 * @ClassName HtmlParseUtil
 * @Description TODO
 * @date 2021/9/30 15:02
 * @Version 1.0
 */

public class HtmlParseUtil {
    public ArrayList<Content> parseJD(String keywords) throws IOException {
        //获取请求
        String url ="https://search.jd.com/Search?keyword="+keywords;
        //解析网页
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        Elements elements = element.getElementsByTag("li");
        ArrayList<Content> goodsList = new ArrayList<>();
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            Content content = new Content(title,img,price);
            goodsList.add(content);
        }
        return goodsList;
    }
}
